# Author: Yu Bin
# Date: 2025/01/02 16:01:39
# E-mail: 853823259@qq.com
my_list = "This is a test string from Andrew".split()
print(my_list)


def change_lower(str_name: str):
    return str_name.lower()


# 可以传递一个比较规则的函数，比较规则发生了改变
print(sorted(my_list, key=change_lower))
my_list.sort(key=change_lower)
print(my_list)
print('-' * 100)

# lambda函数
student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]
print(sorted(student_tuples, key=lambda x: x[2]))
print('-' * 100)


class Student:
    def __init__(self, name, grade, age):
        self.name = name
        self.grade = grade
        self.age = age

    def __repr__(self):
        """
        相对于__str__，可以返回非字符串类型
        :return:
        """
        return repr((self.name, self.grade, self.age))


student_objects = [
    Student('john', 'A', 15),
    Student('jane', 'B', 12),
    Student('dave', 'B', 10),
]
print(student_objects)
print(sorted(student_objects, key=lambda student: student.age))
print('-' * 100)

from operator import itemgetter, attrgetter

print('使用operator系列')
print(sorted(student_tuples, key=itemgetter(1)))
print(sorted(student_objects, key=attrgetter('age')))
print('使用operator系列，多列排序')
print(sorted(student_tuples, key=itemgetter(1, 2)))
print(sorted(student_objects, key=attrgetter('grade', 'age')))
print('-' * 100)
# 字典中混合 list 排序
mydict = {'Li': ['M', 7],
          'Zhang': ['E', 2],
          'Wang': ['P', 3],
          'Du': ['C', 2],
          'Ma': ['C', 9],
          'Zhe': ['H', 7]
          }
print(sorted(mydict.items(), key=lambda x: x[1][1]))
print('-' * 100)
# List 中混合字典排序
gameresult = [{"name": "Bob", "wins": 10, "losses": 3, "rating": 75.00},
              {"name": "David", "wins": 3, "losses": 5, "rating": 57.00},
              {"name": "Carol", "wins": 4, "losses": 5, "rating": 57.00},
              {"name": "Patty", "wins": 9, "losses": 3, "rating": 71.48}]
print(sorted(gameresult, key=lambda x: x['rating']))
print(sorted(gameresult, key=itemgetter("rating", "name")))
print('-' * 100)
